let audioContext = null;

let canplayCallback = null;
let playCallback = null;
let pauseCallback = null;
let stopCallback = null;
let endedCallback = null;
let errorCallback = null;
let timeUpdateCallback = null;
let watingCallback = null;
let prevCallback = null;
let nextCallback = null;

function onCanplay(e) {
	canplayCallback = e;
}

function onPlay(e) {
	playCallback = e;
}

function onPause(e) {
	pauseCallback = e;
}

function onStop(e) {
	stopCallback = e;
}

function onEnded(e) {
	endedCallback = e;
}

function onError(e) {
	errorCallback = e;
}

function onTimeUpdate(e) {
	timeUpdateCallback = e;
}

function onWaiting(e) {
	watingCallback = e;
}

function onPrev(e) {
	prevCallback = e;
}

function onNext(e) {
	nextCallback = e;
}

function initContext() {
	if (audioContext != null) {
		return audioContext;
	}
	audioContext = uni.getBackgroundAudioManager();
	audioContext.onCanplay((e) => {
		if (canplayCallback != null) {
			canplayCallback();
		}
	});
	audioContext.onPlay((e) => {
		if (playCallback != null) {
			playCallback();
		}
	});
	audioContext.onPause((e) => {
		if (pauseCallback != null) {
			pauseCallback();
		}
	});
	audioContext.onStop((e) => {
		if (stopCallback != null) {
			stopCallback();
		}
	});
	audioContext.onEnded((e) => {
		if (endedCallback != null) {
			endedCallback();
		}
	});
	audioContext.onError((e) => {
		if (errorCallback != null) {
			errorCallback();
		}
	});
	audioContext.onTimeUpdate((e) => {
		if (timeUpdateCallback != null) {
			timeUpdateCallback();
		}
	});
	audioContext.onWaiting((e) => {
		if (waitingCallback != null) {
			waitingCallback();
		}
	});
	audioContext.onPrev((e) => {
		if (prevCallback != null) {
			prevCallback();
		}
	});
	audioContext.onNext((e) => {
		if (nextCallback != null) {
			nextCallback();
		}
	});
	return audioContext;
}

const audioUtils = {
	initContext,
	onCanplay,
	onPlay,
	onPause,
	onStop,
	onEnded,
	onError,
	onTimeUpdate,
	onWaiting,
	onPrev,
	onNext
}

export default audioUtils;
